package com.garlicts.framework.binlog.sync.canal;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import com.alibaba.fastjson.JSON;
import com.alibaba.otter.canal.protocol.CanalEntry.Column;
import com.alibaba.otter.canal.protocol.CanalEntry.RowData;
import com.garlicts.framework.binlog.sync.event.EventEnum;
import com.garlicts.framework.binlog.sync.util.NamingUtil;

@Component
public class CanalSyncData {

	private static final Logger logger = LoggerFactory.getLogger(CanalSyncData.class);
	
	@Autowired
	IDbSyncSendService iDbSyncSendService;
	
	private Map<String, Object> populate(String databaseName, String tableName, RowData rowData, EventEnum eventEnum){
		
		Map<String, Object> resultMap = new HashMap<String, Object>(5);
    	Map<String, Object> afterColumnValueMap = new HashMap<String, Object>(10);
    	Map<String, Object> beforeColumnValueMap = new HashMap<String, Object>(10);
    	
    	List<Column> beforeColumnsList = rowData.getBeforeColumnsList();
    	List<Column> afterColumnsList = rowData.getAfterColumnsList();
    	if(CollectionUtils.isEmpty(afterColumnsList)) {
    		return resultMap;
    	}
    	
    	for(Column c : beforeColumnsList) {
    		
    		if(c.getIsNull()) {
    			continue;
    		}
    		String columnHumpStr = NamingUtil.UnderlineToHump(c.getName());
    		beforeColumnValueMap.put(columnHumpStr, c.getValue());
    		
    	}    	
    	
    	for(Column c : afterColumnsList) {
    		
    		if(c.getIsNull()) {
    			continue;
    		}
    		String columnHumpStr = NamingUtil.UnderlineToHump(c.getName());
    		afterColumnValueMap.put(columnHumpStr, c.getValue());
    		
    	}

    	resultMap.put("databaseName", databaseName);
    	resultMap.put("tableName", tableName);
    	resultMap.put("afterColumnValueMap", afterColumnValueMap);
    	resultMap.put("beforeColumnValueMap", beforeColumnValueMap);
    	resultMap.put("operation", eventEnum.getCode());
		
    	return resultMap;
    	
	}
	
	public void sync(String databaseName, String tableName, RowData rowData, EventEnum eventEnum) {
		
		Map<String, Object> populatedMap = populate(databaseName, tableName, rowData, eventEnum);
		iDbSyncSendService.sendMsg(JSON.toJSONString(populatedMap));
//		System.out.println(JSON.toJSONString(populatedMap, true));
		
	}
	
}
